/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2022-08-17     admin       the first version
 */
#include "rtthread.h"
#include "sy_queue.h"
#include "sy_write_thread.h"
#include "board.h"
#include "sy_rs485.h"
#include "sy_uart.h"

cQueue write_send_queue=RT_NULL;
rt_thread_t write_thread=RT_NULL;
write_data_t write_data;

static void Write_Task(void *arg);

int write_thread_init()
{
    if(write_send_queue==RT_NULL)
    {
        write_send_queue=cQueue_Create(10,sizeof(write_data_t), NO_COVER);
        if(write_send_queue==RT_NULL)
        {
            return -1;
        }
    }
    if(write_thread==RT_NULL)
    {
        write_thread=rt_thread_create("write_h", Write_Task,RT_NULL,512, 10, 10);
        if(write_thread==RT_NULL)
        {
            return -2;
        }
        rt_thread_startup(write_thread);
    }
    return 0;
}
int write_push(rt_device_t dev,void *data,unsigned int size)
{
    write_data_t temp;
    if(dev==RT_NULL||data==RT_NULL||size==0)
    {
        return -1;
    }
    if(size>sizeof(temp.data))
    {
        return -2;
    }
    temp.dev=dev;
    temp.size=size;
    rt_memcpy(temp.data,data,size);
    if(cQueue_Push(write_send_queue,&temp,sizeof(temp))!=QUEUE_OK)
    {
        return -3;
    }
    return 0;
}
static void Write_Task(void *arg)
{
    write_data_t rec;
    int ret=0;
    rt_device_t dev=Get_Rs485Dev();

    while(1)
    {
        rt_thread_mdelay(50);
        ret=cQueue_Size(write_send_queue);
        if(ret<=0)
        {
            continue;
        }
        for(int i=0;i<ret;i++)
        {
            int size=cQueue_Receive(write_send_queue,&rec);
            if(rec.size<=0)
            {
                continue;
            }
#if DUBUG
            rt_kprintf("send data[%d]:",rec.size);
            for (int var = 0; var < rec.size; ++var)
            {
                rt_kprintf("%02x ",rec.data[var]);
            }
            rt_kprintf("\n");
#endif
            if(rec.dev!=RT_NULL)
            {

                if(rec.dev==dev)
                {
                    Rs485_Send_Enable();
                }
                rt_device_write(rec.dev, 0, rec.data, rec.size);
                if(rec.dev==dev)
                {
                    rt_thread_mdelay(5);
                    Rs485_Send_Disable();
                }
            }
            rt_memset(&rec,0,sizeof(write_data_t));
            rt_thread_mdelay(50);
        }
    }
}
